package model

import (
	"bytes"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type (
	AuthGroupStationsModel struct {
		db *gorm.DB
	}

	// AuthGroupStations 设备规则
	AuthGroupStations struct {
		ID        int64     `gorm:"primarykey" json:"-"`
		GroupId   int64     `gorm:"index" gorm:"comment: 组ID" json:"group_id"`
		StationId string    `gorm:"index;type:varchar(40)" gorm:"comment: 站点ID" json:"station_id"`
		CreatedAt time.Time `json:"-"`
		UpdatedAt time.Time `json:"-"`
	}
)

func NewAuthGroupStationsModel(gorm *gorm.DB) *AuthGroupStationsModel {
	return &AuthGroupStationsModel{
		db: gorm,
	}
}

func (m *AuthGroupStationsModel) Add(data *AuthGroupStations) error {
	return m.db.Create(data).Error
}

func (m *AuthGroupStationsModel) DelGroupStation(groupId int64) (int64, error) {
	session := m.db.Where("group_id = ?", groupId)
	resp := session.Delete(&AuthGroupStations{})
	return resp.RowsAffected, resp.Error
}

func (m *AuthGroupStationsModel) GetByIds(groupId []int64) ([]AuthGroupStations, error) {
	list := make([]AuthGroupStations, 0, 1)
	session := m.db.Where("group_id in ?", groupId)
	resp := session.Find(&list)
	return append([]AuthGroupStations{}, list...), resp.Error
}

// BatchSave 批量插入数据.
func (m *AuthGroupStationsModel) BatchSave(emps []AuthGroupStations) error {
	var buffer bytes.Buffer
	sql := "insert into auth_group_stations(group_id, station_id, created_at, updated_at) values"
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	datatime := time.Now().Format("2006-01-02 15:04:05")
	for i, e := range emps {
		if i == len(emps)-1 {
			buffer.WriteString(fmt.Sprintf("('%d','%s','%s', '%s');", e.GroupId, e.StationId, datatime, datatime))
		} else {
			buffer.WriteString(fmt.Sprintf("('%d','%s', '%s','%s'),", e.GroupId, e.StationId, datatime, datatime))
		}
	}
	return m.db.Exec(buffer.String()).Error
}

func (m *AuthGroupStationsModel) GetGroupStationByGroupIdAndStationId(groupId int64, stationId string) (AuthGroupStations, error) {
	var groupStation AuthGroupStations
	tx := m.db.Where("group_id = ?", groupId).Where("station_id = ?", stationId).First(&groupStation)
	return groupStation, tx.Error
}

func (m *AuthGroupStationsModel) GetAuthGroupStationsByStationId(stationId string) ([]AuthGroupStations, error) {
	list := make([]AuthGroupStations, 0, 1)
	tx := m.db.Where("station_id = ?", stationId).Find(&list)
	return append([]AuthGroupStations{}, list...), tx.Error
}
